# -*- coding: utf-8 -*-
"""
日志记录配置模块
负责配置和管理系统日志记录
"""

import os
import logging
import logging.handlers
from typing import Optional
from .config import config


class Logger:
    """日志管理类"""
    
    def __init__(self, name: str = "log_analysis_system"):
        """
        初始化日志管理器
        
        Args:
            name: 日志器名称
        """
        self.name = name
        self.logger = self._setup_logger()
    
    def _setup_logger(self) -> logging.Logger:
        """
        设置日志器
        
        Returns:
            配置好的日志器
        """
        logger = logging.getLogger(self.name)
        
        # 避免重复添加处理器
        if logger.handlers:
            return logger
        
        # 设置日志级别
        level = getattr(logging, config.get('logging.level', 'INFO'))
        logger.setLevel(level)
        
        # 创建格式化器
        formatter = logging.Formatter(
            config.get('logging.format', '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        )
        
        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(level)
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)
        
        # 文件处理器
        log_file = config.get('logging.file', 'logs/app.log')
        if log_file:
            # 确保日志目录存在
            log_dir = os.path.dirname(log_file)
            if log_dir and not os.path.exists(log_dir):
                os.makedirs(log_dir)
            
            # 使用RotatingFileHandler进行日志轮转
            max_size = config.get('logging.max_size', 100 * 1024 * 1024)  # 100MB
            backup_count = config.get('logging.backup_count', 5)
            
            file_handler = logging.handlers.RotatingFileHandler(
                log_file,
                maxBytes=max_size,
                backupCount=backup_count,
                encoding='utf-8'
            )
            file_handler.setLevel(level)
            file_handler.setFormatter(formatter)
            logger.addHandler(file_handler)
        
        return logger
    
    def debug(self, message: str, *args, **kwargs) -> None:
        """记录调试日志"""
        self.logger.debug(message, *args, **kwargs)
    
    def info(self, message: str, *args, **kwargs) -> None:
        """记录信息日志"""
        self.logger.info(message, *args, **kwargs)
    
    def warning(self, message: str, *args, **kwargs) -> None:
        """记录警告日志"""
        self.logger.warning(message, *args, **kwargs)
    
    def error(self, message: str, *args, **kwargs) -> None:
        """记录错误日志"""
        self.logger.error(message, *args, **kwargs)
    
    def critical(self, message: str, *args, **kwargs) -> None:
        """记录严重错误日志"""
        self.logger.critical(message, *args, **kwargs)
    
    def exception(self, message: str, *args, **kwargs) -> None:
        """记录异常日志（包含堆栈跟踪）"""
        self.logger.exception(message, *args, **kwargs)


def get_logger(name: str = "log_analysis_system") -> Logger:
    """
    获取日志器实例
    
    Args:
        name: 日志器名称
        
    Returns:
        日志器实例
    """
    return Logger(name)


# 全局日志器实例
logger = get_logger() 